package com.xiaojimao.Config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class RabbitQueueConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 创建名为articleReviewQueue 消息队列
     *
     * @return
     */
    @Bean
    public Queue articleReviewQueue() {
        return new Queue("article.review.queue", true);
    }

    @Bean
    public Queue articleReviewCommentQueue() {
        return new Queue("article.review.comment.queue", true);
    }

    /**
     * articleExchange交换机
     *
     * @return
     */
    @Bean
    public Exchange articleExchange() {
        return new DirectExchange("article.exchange", true, false);
    }

    /**
     * review 作为key 绑定关系
     *
     * @return
     */
    @Bean
    public Binding reviewBinding() {
        return BindingBuilder.bind(articleReviewQueue()).to(articleExchange()).with("review").noargs();
    }

    @Bean
    public Binding reviewCommentBinding() {
        return BindingBuilder.bind(articleReviewQueue()).to(articleExchange()).with("review_comment").noargs();
    }

    /**
     * 当RabbitQueueConfig创建完成后就会执行这个方法
     */
    @PostConstruct
    public void initRabbitTemplate() {

        // 1、只要消息抵达Broker就ack=true
        //     correlationData：当前消息的唯一关联数据(这个是消息的唯一id)
        //     ack：消息是否成功收到
        //     cause：失败的原因

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    log.info("消息实体:{},消息是否成功收到:{}", correlationData, ack);
                } else {
                    log.error("消息实体:{},消息是否成功收到:{},失败的原因:{}", correlationData, ack, cause);
                }
            }
        });

        /**
         * 只要消息没投递到指定的队列，就会触发这个回调
         */
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                log.error("当前消息投递的交换机:{},当前消息投递的路由键:{},当前消息的状态码:{},当前消息文本信息:{}", returnedMessage.getExchange(), returnedMessage.getRoutingKey(), returnedMessage.getReplyCode(), returnedMessage.getReplyText());
            }
        });
    }
}
